<?php
namespace App\Libs\Base;
use \Phalcon\DI;
class Config extends \App\Libs\Base\Singleton
{
    protected function __construct($category = 'web') {
        $this->_init(ucfirst($category));
    }
    public function __get($name) {
        $val = DI::getDefault()->get($this->_getName($name));

        return $val;
    }

    private function _init($category) {
        $configPath = APP_PATH . '/app/configs/' . $category . '/';
        $dir = opendir($configPath);
        $common = 'common.inc.php';
        while(($file = readdir($dir)) !== FALSE) {
            if ($file === '.' || $file === '..' || $file === $common) {
                continue;
            }
            $file = strtolower($file);
            $className = explode('.', $file);
            $class = '\\App\\Configs\\' . $category . '\\' . ucfirst($className[0]);
            if (class_exists($class)) {
                DI::getDefault()->set($this->_getName($className[0]), function() use ($class) {
                    static $confs;
                    if ( ! empty($confs)) {
                        return $confs;
                    }
                    $confs = new AccessObject($class::instance()->configs());
                    return $confs;
                });
            }
        }
        require $configPath . '/' .  $common;
    }

    private function _getName($name) {
        return '__config_' . $name;
    }
}
